#!/bin/sh -efu
#
# mki-sh-functions
#
# This file is part of mkimage
# Copyright (C) 2007-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

if [ -z "${__included_mki_sh_functions:-}" ]; then
__included_mki_sh_functions=1

. shell-error
. shell-args

verbose="${VERBOSE:+-v}"
quiet="${QUIET:+-q}"

workdirname=${WORKDIRNAME:?Work directory name required}
outdirname=${OUTDIRNAME:?Out directory name required}
#cachedirname=${CACHEDIRNAME:?Cache directory name required}

bindir="${TOOLSDIR:?Helper directory required}"
bindir="$(opt_check_dir 'TOOLSDIR' "$bindir")"

curdir="${CURDIR:?Current directory required}"
curdir="$(opt_check_dir 'CURDIR' "$curdir")"

cachedir="${CACHEDIR:?cache required}"
outdir="${OUTDIR:?Output directory required}"
dir="${WORKDIR:?Work directory required}"

if [ -z "${include_without_workdir_check-}" ]; then
	cachedir="$(opt_check_dir 'CACHEDIR' "$cachedir")"
	outdir="$(opt_check_dir 'OUTDIR' "$outdir")"
	dir="$(opt_check_dir 'WORKDIR' "$dir")"
fi

chroot="$dir/chroot"

subdir="$chroot/$WORKDIRNAME"
subchroot="$subdir/chroot"

makefile="${MYMAKEFILE:?makefile required}"
makefile="$(opt_check_read 'MYMAKEFILE' "$makefile")"

[ -s "$makefile" ] ||
	fatal "$makefile: Makefile is empty"

export PATH="$bindir:$PATH"

cp_args=
get_copy_args() {
	[ "$#" -ge 2 ] ||
		fatal "get_copy_args(): more arguments required"

	cp_args=
	[ $(find "$@" -printf '%D\n' 2>/dev/null |sort -u |wc -l) -eq 1 ] ||
		return 0
	cp_args='-l'
}

make_exec() {
	cat > "$1"
	chmod 755 -- "$1"
}

run_chrooted() {
	local rc=0
	make_exec "$1/.host/run_chrooted.sh"
	mki-run "/.host/run_chrooted.sh" || rc=$?
	rm -f -- "$1/.host/run_chrooted.sh"
	return $rc
}

mki_list_pkgs() {
	local r
	for r in "$@"; do
		if [ -f "$r" ]; then
			grep -h '^[[:space:]]*[^#]' "$r" |
				tr ' ' '\n'
		else
			printf '%s\n' "$r"
		fi
	done |
		{
			if [ -z "$NO_SORT_PACKAGES" ]; then
				sort -u
			else
				cat
			fi
		}
}

fi
